package com.shajj.data.rss;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.fetcher.FetcherException;
import com.sun.syndication.fetcher.impl.FeedFetcherCache;
import com.sun.syndication.fetcher.impl.HttpURLFeedFetcher;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;

public class RssHttpURLFeedFetcher extends HttpURLFeedFetcher {

	public RssHttpURLFeedFetcher(FeedFetcherCache feedInfoCache) {
		super(feedInfoCache);
	}

	@Override
	public SyndFeed retrieveFeed(URL feedUrl) throws IllegalArgumentException, IOException, FeedException, FetcherException {
		if (feedUrl == null) {
			throw new IllegalArgumentException("null is not a valid URL");
		}
		InputStream inputStream = null;
		try {
			inputStream = feedUrl.openStream();
			return readSyndFeedFromStream(inputStream);
		} catch (IOException e) {
		} finally {
			if (inputStream != null) {
				inputStream.close();
			}
		}
		return null;
	}

	private SyndFeed readSyndFeedFromStream(InputStream inputStream) throws IOException, IllegalArgumentException, FeedException {
		BufferedInputStream is = new BufferedInputStream(inputStream);
		XmlReader reader = new XmlReader(is, true);
		SyndFeedInput syndFeedInput = new SyndFeedInput();
		syndFeedInput.setPreserveWireFeed(isPreserveWireFeed());
		return syndFeedInput.build(reader);

	}

}
